 /* 
 * File:   StateMachine.cpp
 * Author: josep
 * 
 * Created on 5 / desembre / 2010, 05:42
 */

#include "StateMachine.h"

#ifndef STATEMACHINE_CPP
#define	STATEMACHINE_CPP

template <typename T>
StateMachine<T>::StateMachine() {
    this->state = NULL;
}

template <typename T>
StateMachine<T>::StateMachine(int nStates){
    //states = vector<States*>(6);
    for(int i=0; i<nStates; i++){
        this->states.push_back(State<T>());
        this->states[i].setId(i);
    }
}


template <typename T>
StateMachine<T>::StateMachine(State<T> * state) {
    this->state = state;
}

template <typename T>
StateMachine<T>::StateMachine(const StateMachine<T>& orig) {
    this->state = orig.state;
}

template <typename T>
StateMachine<T>::~StateMachine() {
}

template <typename T>
void StateMachine<T>::processTransition(int transValue){
    //active listeners
    int oldStateId = state->getId();
    State<T> *newState;
    newState = state->getStateFromTransitionValue(transValue);
    if(newState){
        state->runSubscribers(State<T>::SUBSCRIPTION_OUT, transValue, newState->getId());
        state = newState;
        state->runSubscribers(State<T>::SUBSCRIPTION_IN, transValue, oldStateId);
    }
}

template <typename T>
void StateMachine<T>::setInitialState(State<T>* state){
    this->state = state;
}

template <typename T>
void StateMachine<T>::setInitialState(int stateId){
    this->state = getState(stateId);
}

template <typename T>
State<T>* StateMachine<T>::getState(int ind){
    return &(states[ind]);
}

template <typename T>
State<T>* StateMachine<T>::getCurrentState(){
    return state;
}

template <typename T>
State<T>* StateMachine<T>::addState(T *owner){
    states.push_back(State<T>());
    states[states.size()-1].setId(states.size()-1);
    states[states.size()-1].setOwner(owner);
    return &(states[states.size()-1]);
}

#endif	/* STATEMACHINE_CPP */
